import {computed, designPage, reactive} from "@peryl/react-compose";
import {$message, Alert, Button, Input, PageCard, PageCardContent, Select, SelectOption, Space} from "plain-design";
import {copyToClipboard} from "@peryl/utils/copyToClipboard";
import {MonacoEditor} from "../components/MonacoEditor";

export const BuildDifyDbToolsParams = designPage(() => {

  const DEFAULT_PARAM = {};

  const state = reactive({
    operateType: 'query',
    operateData: JSON.stringify({
      page: 0,
      size: 3,
      filters: [{ field: "username", value: "zhangsan", operator: "=" }],
    }, null, 2),
    module: 'llm_user'
  });

  const resultValue = computed(() => {
    return JSON.stringify({
      inputs: {
        operateType: state.operateType,
        operateData: state.operateData,
        module: state.module,
      },
      user: "visitor"
    }, null, 2);
  });

  const isValidJsonString = computed(() => {
    try {
      JSON.parse(state.operateData);
      return true;
    } catch (e) {
      return false;
    }
  });

  const copy = () => {
    if (!isValidJsonString.value) {
      return $message.error("操作参数必须是合法的JSON字符串");
    }
    copyToClipboard(resultValue.value, () => {$message.success("已复制");});
  };

  return () => (
    <PageCard>
      <PageCardContent>
        <Space vertical>
          <div>操作类型：</div>
          <Select v-model={state.operateType}>
            {['query', 'item', 'insert', 'batchInsert', 'update', 'batchUpdate', 'delete'].map(item => (
              <SelectOption label={item} val={item} key={item}/>
            ))}
          </Select>
        </Space>
      </PageCardContent>

      <PageCardContent>
        <Space vertical>
          <div>操作模块：</div>
          <Input v-model={state.module}/>
        </Space>
      </PageCardContent>

      <PageCardContent>
        <Space vertical>
          <div>操作参数：</div>
          <div style={{ height: '200px' }}>
            <MonacoEditor v-model={state.operateData} language="json" fullHeight/>
          </div>
          {!isValidJsonString.value && <Alert label="不是一个合法的JSON字符串" status="error"/>}
        </Space>
      </PageCardContent>
      <PageCardContent>
        <Space vertical>
          <div>
            <span>结果参数</span>
            <Button icon="pi-copy" mode="text" onClick={copy}/>
          </div>
          <Input textarea disabled minHeight="120" modelValue={resultValue.value}/>
        </Space>
      </PageCardContent>
    </PageCard>
  );
});
